<template>
  <el-config-provider :locale="zhCn">
    <div class="customer-pool-container">
      <!-- 筛选条件区域 -->
      <FilterForm v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 选项卡区域 -->
      <el-tabs v-model="activeTab" type="card" class="notice-tabs" @tab-click="handleTabClick">
        <!-- 客户池列表 -->
        <el-tab-pane label="客户池" name="newCustomer">
          <div class="table-section">
            <div class="operation-section">
              <el-tooltip content="新增客户" placement="top">
                <el-button type="primary" @click="handleAdd">新增</el-button>
              </el-tooltip>
              <el-tooltip content="分配客户" placement="top" v-if="userStore.adminRule === 'admin'">
                <el-button type="warning" @click="handleBatchAllocate">分配</el-button>
              </el-tooltip>
              <el-tooltip content="添加好友" placement="top">
                <el-button type="info" :disabled="!selectedCustomers.length" @click="handleBatchAddFriend">添加</el-button>
              </el-tooltip>
              <el-tooltip content="移交失败客户" placement="top">
                <el-button type="danger" :disabled="!selectedCustomers.length" @click="handleBatchMoveToLoss">移交</el-button>
              </el-tooltip>
            </div>
            <el-table
              :data="customerList"
              border
              style="width: 100%"
              v-loading="loading"
              class="custom-table"
              ref="customerTableRef"
              @selection-change="onCustomerSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="shop_name" label="店铺名称" min-width="120" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleView(row)">{{ row.shop_name }}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="order_no" label="订单编号" min-width="140" show-overflow-tooltip />
              <el-table-column prop="buyer_nick" label="买家昵称" min-width="120" show-overflow-tooltip />
              <el-table-column prop="receiver_name" label="收件人" min-width="100" />
              <el-table-column prop="receiver_phone" label="手机号" min-width="120" />
              <el-table-column prop="product_id" label="商品ID" min-width="120" show-overflow-tooltip />
              <el-table-column prop="product_name" label="商品名称" min-width="150" show-overflow-tooltip />
              <el-table-column prop="paid_amount" label="实付金额" min-width="100" align="right">
                <template #default="{ row }">
                  <span>¥{{ row.paid_amount || 0 }}</span>
                </template>
              </el-table-column>

              <!-- <el-table-column prop="create_time" label="创建时间" min-width="160" show-overflow-tooltip /> -->
              <el-table-column prop="accountName" label="分配人" min-width="120" show-overflow-tooltip />
              <el-table-column prop="status" label="状态" min-width="120" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(row)">删除</el-button>

                  <el-popover placement="bottom-end" :width="200" trigger="hover">
                    <template #reference>
                      <el-button type="info" link>更多</el-button>
                    </template>
                    <div class="more-actions">
                      <el-button type="primary" link @click="handleViewLogs(row)" class="more-action-btn"> 日志 </el-button>
                      <el-button type="success" link @click="handleAddWxFriend(row)" class="more-action-btn"> 添加好友 </el-button>
                      <el-button type="warning" link @click="handleReplaceAssignee(row)" class="more-action-btn" v-if="userStore.adminRule === 'admin'">
                        替换
                      </el-button>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 失败客户列表 -->
        <el-tab-pane label="失败客户" name="lossCustomer">
          <div class="table-section">
            <div class="operation-section">
              <el-button type="primary" v-if="userStore.adminRule === 'admin'" :disabled="!selectedLossCustomers.length" @click="handleBatchMoveToCustomer"
                >批量还原</el-button
              >
            </div>
            <el-table
              :data="lossCustomerList"
              border
              style="width: 100%"
              v-loading="loading"
              class="custom-table"
              ref="lossCustomerTableRef"
              @selection-change="onLossCustomerSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="shop_name" label="店铺名称" min-width="120" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleView(row)">{{ row.shop_name }}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="order_no" label="订单编号" min-width="140" show-overflow-tooltip />
              <el-table-column prop="buyer_nick" label="买家昵称" min-width="120" show-overflow-tooltip />
              <el-table-column prop="receiver_name" label="收件人" min-width="100" />
              <el-table-column prop="receiver_phone" label="手机号" min-width="120" />
              <el-table-column prop="product_id" label="商品ID" min-width="120" show-overflow-tooltip />
              <el-table-column prop="product_name" label="商品名称" min-width="150" show-overflow-tooltip />
              <el-table-column prop="paid_amount" label="实付金额" min-width="100" align="right">
                <template #default="{ row }">
                  <span>¥{{ row.paid_amount || 0 }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="create_time" label="创建时间" min-width="160" show-overflow-tooltip />
              <el-table-column prop="message" label="移交操作" min-width="180">
                <template #default="{ row }">
                  <div v-if="row.message" class="message-content" :title="row.message">
                    <div v-for="(line, index) in row.message.split('\n')" :key="index" class="message-line">
                      {{ line }}
                    </div>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleViewLogs(row)"> 日志 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <Pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 客户详情/编辑对话框 -->
      <el-dialog class="editDialog" v-model="dialogVisible" :title="dialogTitle" width="1400px" destroy-on-close>
        <!-- 新增客户时显示选项卡 -->
        <el-tabs v-if="dialogTitle === '新增客户'" v-model="addCustomerTab" type="card" class="add-customer-tabs">
          <!-- 手动新增 -->
          <el-tab-pane label="手动新增" name="manual">
            <el-form ref="formRef" :model="form" :rules="formRules" label-width="130px" class="customer-form">
              <!-- 客户信息 -->
              <div class="form-section">
                <h3 class="section-title">客户信息</h3>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="买家昵称" prop="buyerNick">
                      <el-input v-model="form.buyerNick" :placeholder="isView ? '' : '请输入买家昵称'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="收件人姓名" prop="receiverName">
                      <el-input v-model="form.receiverName" :placeholder="isView ? '' : '请输入收件人姓名'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="收件人手机号" prop="receiverPhone">
                      <el-input v-model="form.receiverPhone" :placeholder="isView ? '' : '请输入收件人手机号'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="虚拟手机号" prop="virtualPhone">
                      <el-input v-model="form.virtualPhone" :placeholder="isView ? '' : '请输入虚拟手机号'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label="省市区" prop="regionCode">
                      <el-cascader
                        v-model="form.regionCode"
                        :options="regionData"
                        :props="{ expandTrigger: 'hover' }"
                        :placeholder="isView ? '' : '请选择省市区'"
                        :disabled="isView"
                        @change="handleRegionChange"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="详细地址" prop="receiverAddress">
                      <el-input v-model="form.receiverAddress" :placeholder="isView ? '' : '请输入详细地址'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 商品订购信息 -->
              <div class="form-section">
                <h3 class="section-title">商品订购信息</h3>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="店铺名称" prop="shopName">
                      <el-input v-model="form.shopName" :placeholder="isView ? '' : '请输入店铺名称'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="订单编号" prop="orderNo">
                      <el-input v-model="form.orderNo" :placeholder="isView ? '' : '请输入订单编号'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="商品名称" prop="productName">
                      <el-input v-model="form.productName" :placeholder="isView ? '' : '请输入商品名称'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="商品ID" prop="productId">
                      <el-input v-model="form.productId" :placeholder="isView ? '' : '请输入商品ID'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="商品简称" prop="productAbbr">
                      <el-input v-model="form.productAbbr" :placeholder="isView ? '' : '请输入商品简称'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="商品规格" prop="productSpec">
                      <el-input v-model="form.productSpec" :placeholder="isView ? '' : '请输入商品规格'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="商品规格简称" prop="productSpecAbbr">
                      <el-input v-model="form.productSpecAbbr" :placeholder="isView ? '' : '请输入商品规格简称'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="商品规格商家编码" prop="productSkuCode">
                      <el-input v-model="form.productSkuCode" :placeholder="isView ? '' : '请输入商品规格商家编码'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="商品商家编码" prop="productSpecCode">
                      <el-input v-model="form.productSpecCode" :placeholder="isView ? '' : '请输入商品商家编码'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="购买数量" prop="quantity">
                      <el-input-number v-model="form.quantity" :placeholder="isView ? '' : '请输入购买数量'" :min="1" :disabled="isView" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="下单时间" prop="orderTime">
                      <el-date-picker
                        v-model="form.orderTime"
                        type="datetime"
                        :placeholder="isView ? '' : '请选择下单时间'"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="子订单状态" prop="subOrderStatus">
                      <el-input v-model="form.subOrderStatus" :placeholder="isView ? '' : '请输入子订单状态'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="快递单号" prop="expressNo">
                      <el-input v-model="form.expressNo" :placeholder="isView ? '' : '请输入快递单号'" :disabled="isView" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="打印时间" prop="printTime">
                      <el-date-picker
                        v-model="form.printTime"
                        type="datetime"
                        :placeholder="isView ? '' : '请选择打印时间'"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="重量" prop="weight">
                      <el-input-number
                        v-model="form.weight"
                        :placeholder="isView ? '' : '请输入重量'"
                        :min="0"
                        :precision="2"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="体积" prop="volume">
                      <el-input-number
                        v-model="form.volume"
                        :placeholder="isView ? '' : '请输入体积'"
                        :min="0"
                        :precision="2"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 订单费用 -->
              <div class="form-section">
                <h3 class="section-title">订单费用</h3>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="实付金额" prop="paidAmount">
                      <el-input-number
                        v-model="form.paidAmount"
                        :placeholder="isView ? '' : '请输入实付金额'"
                        :min="0"
                        :precision="2"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="单价" prop="unitPrice">
                      <el-input-number
                        v-model="form.unitPrice"
                        :placeholder="isView ? '' : '请输入单价'"
                        :min="0"
                        :precision="2"
                        :disabled="isView"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form>
          </el-tab-pane>

          <!-- 批量导入 -->
          <el-tab-pane label="批量导入" name="import">
            <div class="import-container">
              <!-- 步骤指引 -->
              <div class="import-steps">
                <div class="step-item">
                  <div class="step-number">1</div>
                  <div class="step-content">
                    <h4>下载模板</h4>
                    <p>下载标准导入模板</p>
                  </div>
                </div>
                <div class="step-arrow">→</div>
                <div class="step-item">
                  <div class="step-number">2</div>
                  <div class="step-content">
                    <h4>填写数据</h4>
                    <p>按模板格式填写客户信息</p>
                  </div>
                </div>
                <div class="step-arrow">→</div>
                <div class="step-item">
                  <div class="step-number">3</div>
                  <div class="step-content">
                    <h4>上传文件</h4>
                    <p>上传填写好的Excel文件</p>
                  </div>
                </div>
              </div>

              <!-- 模板下载区域 -->
              <div class="template-download">
                <el-button type="primary" @click="handleDownloadTemplate" :loading="downloadLoading"> 下载导入模板 </el-button>
                <p class="download-tip">请先下载模板，按照模板格式填写客户信息</p>
              </div>

              <!-- 文件上传区域 -->
              <div class="file-upload">
                <el-upload
                  ref="uploadRef"
                  class="upload-demo"
                  drag
                  :auto-upload="false"
                  :limit="1"
                  accept=".xlsx,.xls"
                  :on-change="handleFileChange"
                  :file-list="fileList"
                >
                  <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <template #tip>
                    <div class="el-upload__tip">只能上传 xlsx/xls 文件，且不超过 100MB</div>
                  </template>
                </el-upload>
              </div>

              <!-- 上传按钮 -->
              <div class="upload-actions" v-if="fileList.length > 0">
                <el-button type="success" @click="handleConfirmImport" :loading="importLoading" :disabled="!fileList.length || importLoading">
                  {{ importLoading ? '导入中...' : '确定导入' }}
                </el-button>
                <el-button @click="clearFiles">清空文件</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 编辑/查看时显示原表单 -->
        <div v-else>
          <!-- 查看详情时显示选项卡 -->
          <el-tabs v-if="isView" v-model="detailTab" type="card" class="detail-tabs">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <div class="detail-content">
                <!-- 客户信息 -->
                <div class="detail-section">
                  <h3 class="section-title">客户信息</h3>
                  <div class="detail-grid">
                    <div class="detail-item">
                      <span class="detail-label">买家昵称</span>
                      <span class="detail-value">{{ form.buyerNick || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">收件人姓名</span>
                      <span class="detail-value">{{ form.receiverName || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">收件人手机号</span>
                      <span class="detail-value">{{ form.receiverPhone || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">虚拟手机号</span>
                      <span class="detail-value">{{ form.virtualPhone || '-' }}</span>
                    </div>
                    <div class="detail-item detail-item-full">
                      <span class="detail-label">收货地址</span>
                      <span class="detail-value">
                        {{ getFullAddress() || '-' }}
                      </span>
                    </div>
                  </div>
                </div>

                <!-- 商品订购信息 -->
                <div class="detail-section">
                  <h3 class="section-title">商品订购信息</h3>
                  <div class="detail-grid">
                    <div class="detail-item">
                      <span class="detail-label">店铺名称</span>
                      <span class="detail-value">{{ form.shopName || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">订单编号</span>
                      <span class="detail-value">{{ form.orderNo || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品名称</span>
                      <span class="detail-value">{{ form.productName || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品ID</span>
                      <span class="detail-value">{{ form.productId || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品简称</span>
                      <span class="detail-value">{{ form.productAbbr || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品规格</span>
                      <span class="detail-value">{{ form.productSpec || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品规格简称</span>
                      <span class="detail-value">{{ form.productSpecAbbr || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品规格商家编码</span>
                      <span class="detail-value">{{ form.productSkuCode || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">商品商家编码</span>
                      <span class="detail-value">{{ form.productSpecCode || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">购买数量</span>
                      <span class="detail-value">{{ form.quantity || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">下单时间</span>
                      <span class="detail-value">{{ formatDateTime(form.orderTime) || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">子订单状态</span>
                      <span class="detail-value">{{ form.subOrderStatus || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">快递单号</span>
                      <span class="detail-value">{{ form.expressNo || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">打印时间</span>
                      <span class="detail-value">{{ formatDateTime(form.printTime) || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">重量</span>
                      <span class="detail-value">{{ form.weight ? form.weight + 'kg' : '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">体积</span>
                      <span class="detail-value">{{ form.volume ? form.volume + 'm³' : '-' }}</span>
                    </div>
                  </div>
                </div>

                <!-- 订单费用 -->
                <div class="detail-section">
                  <h3 class="section-title">订单费用</h3>
                  <div class="detail-grid">
                    <div class="detail-item">
                      <span class="detail-label">实付金额</span>
                      <span class="detail-value">{{ form.paidAmount ? '¥' + form.paidAmount.toFixed(2) : '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">单价</span>
                      <span class="detail-value">{{ form.unitPrice ? '¥' + form.unitPrice.toFixed(2) : '-' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 操作日志 -->
            <el-tab-pane label="操作日志" name="logs">
              <div class="logs-section">
                <!-- 统计信息 -->
                <div class="stats-overview">
                  <div class="stats-item">
                    <div class="stats-icon add-icon">
                      <el-icon><Plus /></el-icon>
                    </div>
                    <div class="stats-content">
                      <div class="stats-number">{{ customerStatistics.addCount || 0 }}</div>
                      <div class="stats-label">添加次数</div>
                    </div>
                  </div>
                  <div class="stats-item">
                    <div class="stats-icon failed-icon">
                      <el-icon><Document /></el-icon>
                    </div>
                    <div class="stats-content">
                      <div class="stats-number">{{ customerStatistics.addFailedCount || 0 }}</div>
                      <div class="stats-label">添加失败</div>
                    </div>
                  </div>
                  <div class="stats-item">
                    <div class="stats-icon transfer-icon">
                      <el-icon><ArrowRight /></el-icon>
                    </div>
                    <div class="stats-content">
                      <div class="stats-number">{{ customerStatistics.transferCount || 0 }}</div>
                      <div class="stats-label">流转次数</div>
                    </div>
                  </div>
                </div>

                <!-- 新增日志按钮 -->
                <div class="add-log-section">
                  <el-button type="primary" @click="showAddLogDialog" size="small"> 新增日志 </el-button>
                </div>

                <!-- 日志列表 -->
                <div class="logs-container" v-loading="logsLoading">
                  <div v-if="customerLogs.length" class="logs-list">
                    <div v-for="(log, index) in customerLogs" :key="index" class="log-item-inline" :class="getLogItemClass(log.type)">
                      <div class="log-icon-inline">
                        <el-icon>
                          <component :is="getTimelineIcon(log.type)" />
                        </el-icon>
                      </div>
                      <div class="log-content-inline">
                        <div class="log-main-info">
                          <span class="operation-type">{{ getOperationTypeText(log.type) }}</span>
                          <!-- <span class="log-separator">by</span> -->
                          <span class="operation-user">{{ log.accountName }}</span>
                          <span v-if="log.wxtName" class="log-separator">·</span>
                          <span v-if="log.wxtName" class="wxt-name-label">微信昵称:</span>
                          <span v-if="log.wxtName" class="wxt-name-content">{{ log.wxtName }}</span>
                          <span v-if="log.message" class="log-separator">·</span>
                          <span v-if="log.message" class="log-remark-label">备注:</span>
                          <span v-if="log.message" class="log-remark-content">{{ log.message }}</span>
                        </div>
                        <div class="log-time-inline">{{ formatLogTime(log.createTime) }}</div>
                      </div>
                    </div>
                  </div>

                  <!-- 空状态 -->
                  <div v-else-if="!logsLoading" class="empty-state">
                    <el-empty description="暂无操作日志" />
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>

          <!-- 编辑时显示普通表单 -->
          <el-form v-else ref="formRef" :model="form" :rules="formRules" label-width="130px" class="customer-form">
            <!-- 客户信息 -->
            <div class="form-section">
              <h3 class="section-title">客户信息</h3>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="买家昵称" prop="buyerNick">
                    <el-input v-model="form.buyerNick" placeholder="请输入买家昵称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收件人姓名" prop="receiverName">
                    <el-input v-model="form.receiverName" placeholder="请输入收件人姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收件人手机号" prop="receiverPhone">
                    <el-input v-model="form.receiverPhone" placeholder="请输入收件人手机号" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="虚拟手机号" prop="virtualPhone">
                    <el-input v-model="form.virtualPhone" placeholder="请输入虚拟手机号" />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="省市区" prop="regionCode">
                    <el-cascader
                      v-model="form.regionCode"
                      :options="regionData"
                      :props="{ expandTrigger: 'hover' }"
                      placeholder="请选择省市区"
                      @change="handleRegionChange"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="详细地址" prop="receiverAddress">
                    <el-input v-model="form.receiverAddress" placeholder="请输入详细地址" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 商品订购信息 -->
            <div class="form-section">
              <h3 class="section-title">商品订购信息</h3>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="店铺名称" prop="shopName">
                    <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="订单编号" prop="orderNo">
                    <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="form.productName" placeholder="请输入商品名称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="商品ID" prop="productId">
                    <el-input v-model="form.productId" placeholder="请输入商品ID" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品简称" prop="productAbbr">
                    <el-input v-model="form.productAbbr" placeholder="请输入商品简称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品规格" prop="productSpec">
                    <el-input v-model="form.productSpec" placeholder="请输入商品规格" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="商品规格简称" prop="productSpecAbbr">
                    <el-input v-model="form.productSpecAbbr" placeholder="请输入商品规格简称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品规格商家编码" prop="productSkuCode">
                    <el-input v-model="form.productSkuCode" placeholder="请输入商品规格商家编码" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品商家编码" prop="productSpecCode">
                    <el-input v-model="form.productSpecCode" placeholder="请输入商品商家编码" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="购买数量" prop="quantity">
                    <el-input-number v-model="form.quantity" placeholder="请输入购买数量" :min="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="下单时间" prop="orderTime">
                    <el-date-picker v-model="form.orderTime" type="datetime" placeholder="请选择下单时间" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="子订单状态" prop="subOrderStatus">
                    <el-input v-model="form.subOrderStatus" placeholder="请输入子订单状态" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="快递单号" prop="expressNo">
                    <el-input v-model="form.expressNo" placeholder="请输入快递单号" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="打印时间" prop="printTime">
                    <el-date-picker v-model="form.printTime" type="datetime" placeholder="请选择打印时间" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="重量" prop="weight">
                    <el-input-number v-model="form.weight" placeholder="请输入重量" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="体积" prop="volume">
                    <el-input-number v-model="form.volume" placeholder="请输入体积" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 订单费用 -->
            <div class="form-section">
              <h3 class="section-title">订单费用</h3>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="实付金额" prop="paidAmount">
                    <el-input-number v-model="form.paidAmount" placeholder="请输入实付金额" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单价" prop="unitPrice">
                    <el-input-number v-model="form.unitPrice" placeholder="请输入单价" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button v-if="!isView && addCustomerTab === 'manual'" type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分配对话框 -->
      <el-dialog v-model="allocateDialogVisible" :title="currentReplaceCustomerId ? '替换分配人' : '分配客户'" width="500px">
        <div class="allocation-info" style="margin-bottom: 20px; padding: 12px; background-color: #f5f7fa; border-radius: 4px">
          <p style="margin: 0; color: #606266; font-size: 14px">
            <span style="font-weight: 600">分配总数：</span>
            <span style="color: #409eff; font-weight: 600">{{ getAllocationCount() }}</span> 条
          </p>
        </div>

        <el-form :model="allocateForm" label-width="70px">
          <el-form-item label="分配给">
            <el-select v-model="allocateForm.accountIds" multiple placeholder="请选择分配人员" style="width: 100%">
              <el-option v-for="user in userList" :key="user.userId" :label="user.nickName || user.userName" :value="user.userId?.toString()" />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="allocateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAllocate" :loading="allocateLoading">确定分配</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 移交到失败客户备注对话框 -->
      <el-dialog v-model="transferToLossDialogVisible" title="移交到失败客户" width="500px" destroy-on-close>
        <div class="transfer-info" style="margin-bottom: 20px; padding: 12px; background-color: #f5f7fa; border-radius: 4px">
          <p style="margin: 0; color: #606266; font-size: 14px">
            <span style="font-weight: 600">移交客户数：</span>
            <span style="color: #409eff; font-weight: 600">{{ selectedCustomers.length }}</span> 个
          </p>
        </div>
        <el-form :model="transferToLossForm" :rules="transferToLossRules" ref="transferToLossFormRef" label-width="100px">
          <el-form-item label="移交原因" prop="message">
            <el-input
              v-model="transferToLossForm.message"
              type="textarea"
              :rows="4"
              placeholder="请输入移交到失败客户的原因说明"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="transferToLossDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmTransferToLoss" :loading="transferToLossLoading">确定移交</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加好友验证消息对话框 -->
      <el-dialog v-model="addFriendDialogVisible" title="新增好友" width="500px" destroy-on-close>
        <div class="add-friend-info" style="margin-bottom: 20px; padding: 12px; background-color: #f5f7fa; border-radius: 4px">
          <p style="margin: 0; color: #606266; font-size: 14px">
            <span style="font-weight: 600">添加好友数：</span>
            <span style="color: #409eff; font-weight: 600">{{ selectedCustomers.length }}</span> 个
          </p>
        </div>
        <el-form :model="addFriendForm" :rules="addFriendRules" ref="addFriendFormRef" label-width="100px">
          <el-form-item label="验证消息" prop="message">
            <el-input v-model="addFriendForm.message" type="textarea" :rows="3" placeholder="请输入验证消息" maxlength="200" show-word-limit />
            <div style="display: flex; justify-content: flex-end; margin-top: 6px">
              <el-button type="info" plain size="small" @click="openPresetDialog" style="border-radius: 16px">
                <el-icon style="margin-right: 4px"><Document /></el-icon>
                插入预设消息
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addFriendDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAddFriend" :loading="addFriendLoading">确定添加</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 单条添加好友验证消息对话框 -->
      <el-dialog v-model="singleAddFriendDialogVisible" title="新增好友" width="500px" destroy-on-close>
        <div class="add-friend-info" style="margin-bottom: 20px; padding: 12px; background-color: #f5f7fa; border-radius: 4px">
          <p style="margin: 0; color: #606266; font-size: 14px">
            <span style="font-weight: 600">客户信息：</span>
            <span style="color: #409eff; font-weight: 600">{{ currentAddFriendCustomer?.shop_name || '-' }}</span>
          </p>
        </div>
        <el-form :model="singleAddFriendForm" :rules="singleAddFriendRules" ref="singleAddFriendFormRef" label-width="100px">
          <el-form-item label="验证消息" prop="message">
            <el-input v-model="singleAddFriendForm.message" type="textarea" :rows="3" placeholder="请输入验证消息" maxlength="200" show-word-limit />
            <div style="display: flex; justify-content: flex-end; margin-top: 6px">
              <el-button type="info" plain size="small" @click="openSinglePresetDialog" style="border-radius: 16px">
                <el-icon style="margin-right: 4px"><Document /></el-icon>
                插入预设消息
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="singleAddFriendDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmSingleAddFriend" :loading="singleAddFriendLoading">确定添加</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 预设消息弹窗 -->
      <el-dialog v-model="showPresetDialog" title="选择预设消息" width="500px" @close="closePresetDialog">
        <div class="preset-dialog-header">
          <el-input
            v-model="presetFilter"
            placeholder="输入关键词筛选"
            size="small"
            style="width: 240px; margin-right: 12px"
            @keyup.enter="fetchPresetMessages"
          />
          <el-button type="primary" size="small" @click="fetchPresetMessages" :loading="loadingPresetMessages">搜索</el-button>
        </div>
        <div class="preset-card-list">
          <template v-if="presetMessages.length">
            <div
              v-for="msg in presetMessages"
              :key="msg.id"
              class="preset-card-item"
              :class="{ 'is-selected': selectedPresetMsg && selectedPresetMsg.id === msg.id }"
              @click="selectPresetRow(msg)"
              :title="msg.message"
            >
              <div class="msg-content" :class="{ expanded: hoveredCardId === msg.id }" @mouseenter="hoveredCardId = msg.id" @mouseleave="hoveredCardId = null">
                {{ msg.message }}
              </div>
              <span v-if="selectedPresetMsg && selectedPresetMsg.id === msg.id" class="selected-icon">✔</span>
            </div>
          </template>
          <div v-else class="no-preset-messages-card">暂无匹配的预设消息</div>
        </div>
        <div class="preset-dialog-footer">
          <el-pagination
            background
            layout="prev, pager, next, total"
            :current-page="presetPage.current"
            :page-size="presetPage.size"
            :total="presetPage.total"
            @current-change="handlePresetPageChange"
            small
          />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showPresetDialog = false">取消</el-button>
            <el-button type="primary" :disabled="!selectedPresetMsg" @click="confirmPresetMsg">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加客户池日志对话框 -->
      <el-dialog v-model="addLogDialogVisible" title="新增客户日志" width="500px" destroy-on-close>
        <el-form ref="addLogFormRef" :model="addLogForm" :rules="addLogRules" label-width="80px">
          <el-form-item label="日志内容" prop="remark">
            <el-input v-model="addLogForm.remark" type="textarea" :rows="4" placeholder="请输入日志内容..." maxlength="500" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addLogDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddLog" :loading="addLogLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled, Download, Document, ArrowRight, Setting, Plus } from '@element-plus/icons-vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { regionData } from 'element-china-area-data';
import { useUserStore } from '@/store';

const userStore = useUserStore();

import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import {
  getCustomerPoolList,
  addCustomerPool,
  updateCustomerPool,
  deleteCustomerPool,
  importCustomerPool,
  allocateCustomerPool,
  batchAddWxFriend,
  moveToLossPool,
  moveToCustomerPool,
  getAssignableUsers,
  getCustomerPoolLogs,
  getCustomerPoolSum,
  addCustomerPoolLog,
  type CustomerPool,
  type CustomerPoolQueryParams,
  type CustomerPoolLog,
  type CustomerPoolLogsResponse,
  type CustomerPoolStatistics,
  type User,
  type AddCustomerPoolLogParams
} from '@/api/userMange/customerPool';
import { getAuthenticationList } from '@/api/userRate/friendVerify';

// 选项卡
const activeTab = ref('newCustomer');

// 筛选表单类型
interface FilterFormType {
  shopName: string;
  orderNo: string;
  buyerNick: string;
  receiverName: string;
  receiverPhone: string;
  productId: string;
  status: string;
  type: string;
  accountType: string;
}

// 筛选表单
const filterForm = reactive<FilterFormType>({
  shopName: '',
  orderNo: '',
  buyerNick: '',
  receiverName: '',
  receiverPhone: '',
  productId: '',
  status: '',
  type: '1', // 默认客户池
  accountType: ''
});

// 筛选表单配置
const formItems = computed<FormItem[]>(() => [
  {
    type: 'input',
    prop: 'shopName',
    label: '店铺名称',
    placeholder: '请输入店铺名称'
  },
  {
    type: 'input',
    prop: 'orderNo',
    label: '订单编号',
    placeholder: '请输入订单编号'
  },
  {
    type: 'input',
    prop: 'buyerNick',
    label: '买家昵称',
    placeholder: '请输入买家昵称'
  },
  {
    type: 'input',
    prop: 'receiverName',
    label: '收件人',
    placeholder: '请输入收件人姓名'
  },
  {
    type: 'input',
    prop: 'receiverPhone',
    label: '手机号',
    placeholder: '请输入手机号'
  },
  {
    type: 'input',
    prop: 'productId',
    label: '商品ID',
    placeholder: '请输入商品ID'
  },
  {
    type: 'select',
    prop: 'status',
    label: '状态',
    placeholder: '请选择状态',
    options: [
      { label: '全部', value: '' },
      { label: '待添加', value: '1' },
      { label: '添加中', value: '2' },
      { label: '添加成功', value: '3' },
      { label: '添加失败', value: '4' }
    ]
  }
]);

// 表格数据
const loading = ref(false);
const customerList = ref<CustomerPool[]>([]);
const lossCustomerList = ref<CustomerPool[]>([]);
const selectedCustomers = ref<CustomerPool[]>([]);
const selectedLossCustomers = ref<CustomerPool[]>([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isView = ref(false);
const submitLoading = ref(false);
const addCustomerTab = ref('manual'); // 新增客户选项卡：manual-手动新增，import-批量导入

// 表单
const formRef = ref();
const form = reactive<CustomerPool & { regionCode?: string[] }>({
  shopName: '',
  orderNo: '',
  buyerNick: '',
  receiverName: '',
  receiverPhone: '',
  virtualPhone: '',
  receiverProvince: '',
  receiverCity: '',
  receiverDistrict: '',
  receiverAddress: '',
  orderTime: undefined,
  expressNo: '',
  paidAmount: 0,
  productName: '',
  productId: '',
  productAbbr: '',
  productSkuCode: '',
  productSpec: '',
  productSpecAbbr: '',
  productSpecCode: '',
  quantity: 1,
  unitPrice: 0,
  subOrderStatus: '',
  printTime: undefined,
  weight: 0,
  volume: 0,
  type: '1',
  regionCode: []
});

// 表单验证规则
const formRules = {
  shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  buyerNick: [{ required: true, message: '请输入买家昵称', trigger: 'blur' }],
  receiverName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入收件人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
};

// 导入相关变量（用于新增客户对话框中的批量导入选项卡）
const importLoading = ref(false);
const uploadRef = ref();
const fileList = ref<any[]>([]);

// 导入相关变量
const downloadLoading = ref(false);

// 分配对话框
const allocateDialogVisible = ref(false);
const allocateLoading = ref(false);
const allocateForm = reactive({
  accountIds: [] as string[]
});
const userList = ref<User[]>([]);

// 移交到失败客户对话框
const transferToLossDialogVisible = ref(false);
const transferToLossLoading = ref(false);
const transferToLossFormRef = ref();
const transferToLossForm = reactive({
  message: ''
});
const transferToLossRules = {
  message: [{ required: true, message: '请输入移交原因', trigger: 'blur' }]
};

// 添加好友对话框
const addFriendDialogVisible = ref(false);
const addFriendLoading = ref(false);
const addFriendFormRef = ref();
const addFriendForm = reactive({
  message: ''
});
const addFriendRules = {
  message: [{ required: true, message: '请输入验证消息', trigger: 'blur' }]
};

// 单条添加好友对话框
const singleAddFriendDialogVisible = ref(false);
const singleAddFriendLoading = ref(false);
const singleAddFriendFormRef = ref();
const currentAddFriendCustomer = ref<CustomerPool | null>(null);
const singleAddFriendForm = reactive({
  message: ''
});
const singleAddFriendRules = {
  message: [{ required: true, message: '请输入验证消息', trigger: 'blur' }]
};

// 预设消息相关
const showPresetDialog = ref(false);
const presetMessages = ref<any[]>([]);
const selectedPresetMsg = ref<any>(null);
const presetFilter = ref('');
const loadingPresetMessages = ref(false);
const hoveredCardId = ref<number | null>(null);

// 添加客户池日志相关
const addLogDialogVisible = ref(false);
const addLogLoading = ref(false);
const addLogFormRef = ref();
const addLogForm = reactive({
  remark: ''
});

// 添加日志表单验证规则
const addLogRules = {
  remark: [
    { required: true, message: '请输入日志内容', trigger: 'blur' },
    { min: 1, max: 500, message: '日志内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
};
const presetPage = reactive({
  current: 1,
  size: 10,
  total: 0
});
const currentReplaceCustomerId = ref<number | null>(null);
const totalCustomerCount = ref(0); // 总客户数（用于分配确认）

// 详情选项卡
const detailTab = ref('basic');

// 日志相关
const customerLogs = ref<CustomerPoolLog[]>([]);
const customerStatistics = ref<CustomerPoolStatistics>({});
const logsLoading = ref(false);

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      shopName: filterForm.shopName,
      orderNo: filterForm.orderNo,
      buyerNick: filterForm.buyerNick,
      receiverName: filterForm.receiverName,
      receiverPhone: filterForm.receiverPhone,
      status: filterForm.status,
      type: filterForm.type,
      accountType: filterForm.accountType
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === '' || params[key as keyof typeof params] === null || params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log('搜索参数:', params);

    const res = await getCustomerPoolList(params);
    if (activeTab.value === 'newCustomer') {
      customerList.value = res.data.records;
    } else {
      lossCustomerList.value = res.data.records;
    }
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 选项卡切换
const handleTabClick = (tab: any) => {
  activeTab.value = tab.props.name;
  filterForm.type = tab.props.name === 'newCustomer' ? '1' : '2';
  currentPage.value = 1;
  getList();
};

// 筛选相关
const handleFilterChange = (newFilterForm: any) => {
  // 更新筛选条件
  Object.assign(filterForm, newFilterForm);
};

const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

const resetFilter = () => {
  Object.assign(filterForm, {
    shopName: '',
    orderNo: '',
    buyerNick: '',
    receiverName: '',
    receiverPhone: '',
    status: '',
    type: activeTab.value === 'newCustomer' ? '1' : '2',
    accountType: ''
  });
  currentPage.value = 1;
  pageSize.value = 10;
  getList();
};

// 分页
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  getList();
};

// 表格选择
const onCustomerSelectionChange = (selection: CustomerPool[]) => {
  selectedCustomers.value = selection;
};

const onLossCustomerSelectionChange = (selection: CustomerPool[]) => {
  selectedLossCustomers.value = selection;
};

// 省市区级联选择变化处理
const handleRegionChange = (value: any) => {
  if (value && Array.isArray(value) && value.length >= 3) {
    // 根据选择的地区代码获取对应的地区名称
    const getRegionName = (code: string, data: any[]): string => {
      try {
        for (const item of data) {
          if (item && item.value === code) {
            return item.label || '';
          }
          if (item && item.children && Array.isArray(item.children)) {
            const result = getRegionName(code, item.children);
            if (result) return result;
          }
        }
      } catch (error) {
        console.error('查找地区名称时出错:', error);
      }
      return '';
    };

    try {
      form.receiverProvince = getRegionName(value[0], regionData);
      form.receiverCity = getRegionName(value[1], regionData);
      form.receiverDistrict = getRegionName(value[2], regionData);
    } catch (error) {
      console.error('设置地区信息时出错:', error);
      form.receiverProvince = '';
      form.receiverCity = '';
      form.receiverDistrict = '';
    }
  } else {
    form.receiverProvince = '';
    form.receiverCity = '';
    form.receiverDistrict = '';
  }
};

// 根据省市区名称获取地区代码
const getRegionCodeByName = (province: string, city: string, district: string): string[] => {
  const result: string[] = [];

  try {
    // 查找省份
    for (const provinceItem of regionData) {
      if (provinceItem && provinceItem.label === province) {
        result.push(provinceItem.value);

        // 查找城市
        if (provinceItem.children && Array.isArray(provinceItem.children)) {
          for (const cityItem of provinceItem.children) {
            if (cityItem && cityItem.label === city) {
              result.push(cityItem.value);

              // 查找区县
              if (cityItem.children && Array.isArray(cityItem.children)) {
                for (const districtItem of cityItem.children) {
                  if (districtItem && districtItem.label === district) {
                    result.push(districtItem.value);
                    break;
                  }
                }
              }
              break;
            }
          }
        }
        break;
      }
    }
  } catch (error) {
    console.error('获取地区代码时出错:', error);
  }

  return result;
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    shopName: '',
    orderNo: '',
    buyerNick: '',
    receiverName: '',
    receiverPhone: '',
    virtualPhone: '',
    receiverProvince: '',
    receiverCity: '',
    receiverDistrict: '',
    receiverAddress: '',
    orderTime: undefined,
    expressNo: '',
    paidAmount: 0,
    productName: '',
    productId: '',
    productAbbr: '',
    productSkuCode: '',
    productSpec: '',
    productSpecAbbr: '',
    productSpecCode: '',
    quantity: 1,
    unitPrice: 0,
    subOrderStatus: '',
    printTime: undefined,
    weight: 0,
    volume: 0,
    type: '1',
    regionCode: []
  });
  formRef.value?.clearValidate();
};

// 新增
const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增客户';
  isView.value = false;
  addCustomerTab.value = 'manual'; // 默认选择手动新增
  dialogVisible.value = true;
};

// 查看详情
const handleView = (row: any) => {
  try {
    // 将后端下划线字段转换为前端驼峰字段
    const formData = {
      id: row.id,
      shopName: row.shop_name,
      orderNo: row.order_no,
      buyerNick: row.buyer_nick,
      receiverName: row.receiver_name,
      receiverPhone: row.receiver_phone,
      virtualPhone: row.virtual_phone,
      receiverProvince: row.receiver_province,
      receiverCity: row.receiver_city,
      receiverDistrict: row.receiver_district,
      receiverAddress: row.receiver_address,
      orderTime: row.order_time ? new Date(row.order_time) : undefined,
      expressNo: row.express_no,
      paidAmount: parseFloat(row.paid_amount || 0),
      productName: row.product_name,
      productId: row.product_id,
      productAbbr: row.product_abbr,
      productSkuCode: row.product_sku_code,
      productSpec: row.product_spec,
      productSpecAbbr: row.product_spec_abbr,
      productSpecCode: row.product_spec_code,
      quantity: parseInt(row.quantity || 1),
      unitPrice: parseFloat(row.unit_price || 0),
      subOrderStatus: row.sub_order_status,
      printTime: row.print_time ? new Date(row.print_time) : undefined,
      weight: parseFloat(row.weight || 0),
      volume: parseFloat(row.volume || 0),
      type: row.type
    };

    Object.assign(form, formData);

    // 设置级联选择器的值
    if (row.receiver_province && row.receiver_city && row.receiver_district) {
      form.regionCode = getRegionCodeByName(row.receiver_province, row.receiver_city, row.receiver_district);
    } else {
      form.regionCode = [];
    }
    dialogTitle.value = '客户详情';
    isView.value = true;
    detailTab.value = 'basic'; // 默认显示基本信息
    dialogVisible.value = true;

    // 加载操作日志
    if (row.id) {
      loadCustomerLogs(row.id);
    }
  } catch (error) {
    console.error('查看详情时出错:', error);
    ElMessage.error('查看详情失败');
  }
};

// 查看操作日志
const handleViewLogs = (row: any) => {
  try {
    // 将后端下划线字段转换为前端驼峰字段
    const formData = {
      id: row.id,
      shopName: row.shop_name,
      orderNo: row.order_no,
      buyerNick: row.buyer_nick,
      receiverName: row.receiver_name,
      receiverPhone: row.receiver_phone,
      virtualPhone: row.virtual_phone,
      receiverProvince: row.receiver_province,
      receiverCity: row.receiver_city,
      receiverDistrict: row.receiver_district,
      receiverAddress: row.receiver_address,
      orderTime: row.order_time ? new Date(row.order_time) : undefined,
      expressNo: row.express_no,
      paidAmount: parseFloat(row.paid_amount || 0),
      productName: row.product_name,
      productId: row.product_id,
      productAbbr: row.product_abbr,
      productSkuCode: row.product_sku_code,
      productSpec: row.product_spec,
      productSpecAbbr: row.product_spec_abbr,
      productSpecCode: row.product_spec_code,
      quantity: parseInt(row.quantity || 1),
      unitPrice: parseFloat(row.unit_price || 0),
      subOrderStatus: row.sub_order_status,
      printTime: row.print_time ? new Date(row.print_time) : undefined,
      weight: parseFloat(row.weight || 0),
      volume: parseFloat(row.volume || 0),
      type: row.type,
      createTime: row.create_time,
      updateTime: row.update_time,
      status: row.status,
      message: row.message
    };

    Object.assign(form, formData);

    // 设置级联选择器的值
    if (row.receiver_province && row.receiver_city && row.receiver_district) {
      form.regionCode = getRegionCodeByName(row.receiver_province, row.receiver_city, row.receiver_district);
    } else {
      form.regionCode = [];
    }

    dialogTitle.value = '操作日志';
    isView.value = true;
    detailTab.value = 'logs'; // 直接显示操作日志标签页
    dialogVisible.value = true;

    // 加载操作日志
    if (row.id) {
      loadCustomerLogs(row.id);
    }
  } catch (error) {
    console.error('查看操作日志时出错:', error);
    ElMessage.error('查看操作日志失败');
  }
};

// 编辑
const handleEdit = (row: any) => {
  try {
    // 将后端下划线字段转换为前端驼峰字段
    const formData = {
      id: row.id,
      shopName: row.shop_name,
      orderNo: row.order_no,
      buyerNick: row.buyer_nick,
      receiverName: row.receiver_name,
      receiverPhone: row.receiver_phone,
      virtualPhone: row.virtual_phone,
      receiverProvince: row.receiver_province,
      receiverCity: row.receiver_city,
      receiverDistrict: row.receiver_district,
      receiverAddress: row.receiver_address,
      orderTime: row.order_time ? new Date(row.order_time) : undefined,
      expressNo: row.express_no,
      paidAmount: parseFloat(row.paid_amount || 0),
      productName: row.product_name,
      productId: row.product_id,
      productAbbr: row.product_abbr,
      productSkuCode: row.product_sku_code,
      productSpec: row.product_spec,
      productSpecAbbr: row.product_spec_abbr,
      productSpecCode: row.product_spec_code,
      quantity: parseInt(row.quantity || 1),
      unitPrice: parseFloat(row.unit_price || 0),
      subOrderStatus: row.sub_order_status,
      printTime: row.print_time ? new Date(row.print_time) : undefined,
      weight: parseFloat(row.weight || 0),
      volume: parseFloat(row.volume || 0),
      type: row.type
    };

    Object.assign(form, formData);

    // 设置级联选择器的值
    if (row.receiver_province && row.receiver_city && row.receiver_district) {
      form.regionCode = getRegionCodeByName(row.receiver_province, row.receiver_city, row.receiver_district);
    } else {
      form.regionCode = [];
    }
    dialogTitle.value = '编辑客户';
    isView.value = false;
    dialogVisible.value = true;
  } catch (error) {
    console.error('编辑时出错:', error);
    ElMessage.error('编辑失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitLoading.value = true;

    // 准备提交数据
    const submitData = {
      id: form.id,
      shopName: form.shopName,
      orderNo: form.orderNo,
      buyerNick: form.buyerNick,
      receiverName: form.receiverName,
      receiverPhone: form.receiverPhone,
      virtualPhone: form.virtualPhone,
      receiverProvince: form.receiverProvince,
      receiverCity: form.receiverCity,
      receiverDistrict: form.receiverDistrict,
      receiverAddress: form.receiverAddress,
      orderTime: formatDateTime(form.orderTime),
      expressNo: form.expressNo,
      paidAmount: form.paidAmount,
      productName: form.productName,
      productId: form.productId,
      productAbbr: form.productAbbr,
      productSkuCode: form.productSkuCode,
      productSpec: form.productSpec,
      productSpecAbbr: form.productSpecAbbr,
      productSpecCode: form.productSpecCode,
      quantity: form.quantity,
      unitPrice: form.unitPrice,
      subOrderStatus: form.subOrderStatus,
      printTime: formatDateTime(form.printTime),
      weight: form.weight,
      volume: form.volume,
      type: activeTab.value === 'newCustomer' ? '1' : '2'
    };

    if (form.id) {
      await updateCustomerPool(submitData);
      ElMessage.success('编辑成功');
    } else {
      await addCustomerPool(submitData);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    getList();
  } catch (error) {
    ElMessage.error('操作失败');
  } finally {
    submitLoading.value = false;
  }
};

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteCustomerPool({ id: row.id! });
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 日志相关函数
const loadCustomerLogs = async (poolId: number) => {
  try {
    logsLoading.value = true;
    const response = await getCustomerPoolLogs(poolId);
    customerLogs.value = response.data.page.records || [];
    customerStatistics.value = response.data.statistics || {};
  } catch (error) {
    console.error('获取日志失败:', error);
    ElMessage.error('获取操作日志失败');
    customerLogs.value = [];
    customerStatistics.value = {};
  } finally {
    logsLoading.value = false;
  }
};

// 获取操作类型标签样式
const getOperationTypeTag = (type?: string) => {
  const typeMap: Record<string, string> = {
    '1': 'success', // 添加操作
    '2': 'warning' // 移交到失败客户池
  };
  return typeMap[type || ''] || 'info';
};

// 获取操作类型文本
const getOperationTypeText = (type?: string) => {
  const typeMap: Record<string, string> = {
    '1': '添加操作',
    '2': '移交到失败客户池',
    '3': '添加失败',
    '4': '跟进记录'
  };
  return typeMap[type || ''] || '未知操作';
};

// 获取时间轴类型
const getTimelineType = (type?: string) => {
  const typeMap: Record<string, string> = {
    '1': 'success', // 添加操作
    '2': 'warning' // 转移到失败客户池
  };
  return typeMap[type || ''] || 'info';
};

// 获取时间轴图标
const getTimelineIcon = (type?: string) => {
  const iconMap: Record<string, any> = {
    '1': Plus, // 添加操作
    '2': ArrowRight // 转移操作
  };
  return iconMap[type || ''] || Document;
};

// 获取日志项样式类
const getLogItemClass = (type?: string) => {
  const classMap: Record<string, string> = {
    '1': 'log-item-success', // 添加操作
    '2': 'log-item-warning' // 转移操作
  };
  return classMap[type || ''] || 'log-item-default';
};

// 格式化日志时间
const formatLogTime = (timeStr?: string) => {
  if (!timeStr) return '';

  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000));
    return `${minutes}分钟前`;
  }

  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    return `${hours}小时前`;
  }

  // 超过1天，显示具体时间
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 上传前检查
const beforeUpload = (file: any) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
  const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!');
    return false;
  }
  if (!isLt100M) {
    ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
    return false;
  }
  return false; // 阻止自动上传
};

// 清空文件
const clearFiles = () => {
  fileList.value = [];
  uploadRef.value?.clearFiles();
};

const handleFileChange = (file: any) => {
  // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.raw && file.raw.size > maxSize) {
    ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.raw.size / 1024 / 1024).toFixed(2)}MB`);
    return;
  }

  fileList.value = [file];
};

// 获取本地存储中的微信ID
const getCurrentWxId = (): string => {
  try {
    const msgProfile = localStorage.getItem('msgprofile');
    if (msgProfile) {
      const profile = JSON.parse(msgProfile);
      return profile.wx_id || '';
    }
    return '';
  } catch (error) {
    console.error('获取微信ID失败:', error);
    return '';
  }
};

// 时间格式化函数
const formatDateTime = (date: Date | string | undefined | null): string | undefined => {
  if (!date) return undefined;

  // 如果已经是字符串格式，直接返回
  if (typeof date === 'string') return date;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取完整地址
const getFullAddress = () => {
  const parts = [];
  if (form.receiverProvince) parts.push(form.receiverProvince);
  if (form.receiverCity) parts.push(form.receiverCity);
  if (form.receiverDistrict) parts.push(form.receiverDistrict);
  if (form.receiverAddress) parts.push(form.receiverAddress);
  return parts.join(' ');
};

// 下载导入模板
const handleDownloadTemplate = () => {
  try {
    window.open(`${import.meta.env.VITE_GLOB_APP_IMG_URL}juliao/excel/客户池导入模板.xlsx`, '_blank');
    ElMessage.success('模板下载中...');
  } catch (error) {
    ElMessage.error('模板下载失败');
  }
};

const handleConfirmImport = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }

  try {
    // 确认导入操作
    await ElMessageBox.confirm('确定要导入选中的文件吗？', '确认导入', {
      confirmButtonText: '确定导入',
      cancelButtonText: '取消',
      type: 'warning'
    });

    importLoading.value = true;
    await importCustomerPool(fileList.value[0].raw);
    ElMessage.success('导入成功');

    // 清空文件列表
    fileList.value = [];

    // 关闭新增客户对话框
    dialogVisible.value = false;

    // 刷新列表数据
    getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('导入失败:', error);

      // 提取错误信息
      let errorMessage = '导入失败';
      if (error?.message) {
        errorMessage = error.message;
      } else if (error?.response?.data?.msg) {
        errorMessage = error.response.data.msg;
      } else if (typeof error === 'string') {
        errorMessage = error;
      }

      ElMessage.error(errorMessage);
    }
  } finally {
    importLoading.value = false;
  }
};

// 获取可分配用户列表
const loadAssignableUsers = async () => {
  try {
    const response = await getAssignableUsers();
    console.log(response);

    userList.value = response.data;
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 获取总客户数
const getTotalCustomerCount = async () => {
  try {
    const params: any = {
      shopName: filterForm.shopName,
      orderNo: filterForm.orderNo,
      buyerNick: filterForm.buyerNick,
      receiverName: filterForm.receiverName,
      receiverPhone: filterForm.receiverPhone,
      status: filterForm.status,
      type: filterForm.type,
      accountType: filterForm.accountType
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === '' || params[key as keyof typeof params] === null || params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    const response = await getCustomerPoolSum(params);
    totalCustomerCount.value = response.data;
    return response.data;
  } catch (error) {
    console.error('获取总条数失败:', error);
    return 0;
  }
};

// 获取分配总数
const getAllocationCount = () => {
  if (currentReplaceCustomerId.value) {
    return 1; // 单条替换
  } else if (selectedCustomers.value.length > 0) {
    return selectedCustomers.value.length;
  } else {
    return totalCustomerCount.value || customerList.value.length;
  }
};

// 分配
const handleBatchAllocate = async () => {
  if (!selectedCustomers.value.length) {
    // 没有选中客户时，先获取总条数，然后询问是否给所有客户分配
    try {
      const totalCount = await getTotalCustomerCount();

      await ElMessageBox.confirm(`当前没有选中任何客户，是否要给所有客户进行分配？（共 ${totalCount} 条）`, '分配确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });

      // 用户确认后，获取用户列表并打开分配对话框
      await loadAssignableUsers();
      allocateForm.accountIds = [];
      allocateDialogVisible.value = true;
    } catch (error) {
      // 用户取消操作
      return;
    }
  } else {
    // 有选中客户时，正常流程
    await loadAssignableUsers();
    allocateForm.accountIds = [];
    allocateDialogVisible.value = true;
  }
};

const handleConfirmAllocate = async () => {
  if (!allocateForm.accountIds.length) {
    ElMessage.warning('请选择分配人员');
    return;
  }

  try {
    allocateLoading.value = true;

    let ids: string;
    let successMessage: string;

    // 判断是单条替换还是分配
    if (currentReplaceCustomerId.value) {
      // 单条替换
      ids = currentReplaceCustomerId.value.toString();
      successMessage = '成功替换分配人';
    } else if (selectedCustomers.value.length > 0) {
      // 有选中客户，使用选中的客户ID
      ids = selectedCustomers.value.map((item: any) => item.id).join(',');
      successMessage = `成功分配 ${selectedCustomers.value.length} 个客户`;
    } else {
      // 没有选中客户，使用所有客户的ID
      ids = '';
      successMessage = `成功分配 ${customerList.value.length} 个客户`;
    }

    const accountIds = allocateForm.accountIds.join(',');
    await allocateCustomerPool({ ids, accountIds });

    ElMessage.success(successMessage);
    allocateDialogVisible.value = false;

    // 清空状态
    selectedCustomers.value = [];
    currentReplaceCustomerId.value = null;

    getList();
  } catch (error: any) {
    console.log(error.message);

    // 提取错误信息
    let errorMessage = '分配失败';
    if (error?.message) {
      errorMessage = error.message;
    } else if (error?.response?.data?.msg) {
      errorMessage = error.response.data.msg;
    } else if (typeof error === 'string') {
      errorMessage = error;
    }

    ElMessage.error(errorMessage);
  } finally {
    allocateLoading.value = false;
  }
};

// 替换分配人
const handleReplaceAssignee = async (row: CustomerPool) => {
  try {
    await loadAssignableUsers();
    allocateForm.accountIds = [];
    allocateDialogVisible.value = true;
    currentReplaceCustomerId.value = row.id || null;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};

// 添加微信好友
const handleAddWxFriend = async (row: any) => {
  // 设置当前客户信息并打开对话框
  currentAddFriendCustomer.value = row;
  singleAddFriendForm.message = '';
  singleAddFriendDialogVisible.value = true;
};

// 确认单条添加好友
const handleConfirmSingleAddFriend = async () => {
  try {
    // 验证表单
    await singleAddFriendFormRef.value?.validate();

    singleAddFriendLoading.value = true;

    const wxId = getCurrentWxId();
    if (!wxId) {
      ElMessage.error('未找到微信账号信息，请重新登录');
      return;
    }

    const res = await batchAddWxFriend({
      ids: String(currentAddFriendCustomer.value?.id!),
      wxId,
      message: singleAddFriendForm.message
    });

    ElMessage.info((res as any).msg || '添加好友成功');
    singleAddFriendDialogVisible.value = false;
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加好友失败');
    }
  } finally {
    singleAddFriendLoading.value = false;
  }
};

// 批量添加微信好友
const handleBatchAddFriend = async () => {
  if (!selectedCustomers.value.length) {
    ElMessage.warning('请选择要添加好友的客户');
    return;
  }

  // 重置表单并打开对话框
  addFriendForm.message = '';
  addFriendDialogVisible.value = true;
};

// 确认添加好友
const handleConfirmAddFriend = async () => {
  try {
    // 验证表单
    await addFriendFormRef.value?.validate();

    addFriendLoading.value = true;

    // 获取微信ID
    const wxId = getCurrentWxId();
    if (!wxId) {
      ElMessage.error('未找到微信账号信息，请重新登录');
      return;
    }

    // 准备批量添加的数据
    const ids = selectedCustomers.value.map((customer) => customer.id).join(',');

    // 调用批量添加接口
    const res = await batchAddWxFriend({
      ids,
      wxId,
      message: addFriendForm.message
    });

    // 显示结果
    ElMessage.info((res as any).msg || '添加好友成功');

    // 刷新列表
    getList();

    addFriendDialogVisible.value = false;
    selectedCustomers.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加好友失败');
    }
  } finally {
    addFriendLoading.value = false;
  }
};

// 批量移交到失败客户
const handleBatchMoveToLoss = async () => {
  if (!selectedCustomers.value.length) {
    ElMessage.warning('请选择要移交的客户');
    return;
  }

  // 重置表单并打开对话框
  transferToLossForm.message = '';
  transferToLossDialogVisible.value = true;
};

// 确认移交到失败客户
const handleConfirmTransferToLoss = async () => {
  try {
    // 验证表单
    await transferToLossFormRef.value?.validate();

    transferToLossLoading.value = true;

    // 获取当前操作人的微信ID
    const wxId = getCurrentWxId();
    if (!wxId) {
      ElMessage.error('未找到微信账号信息，请重新登录');
      return;
    }

    const ids = selectedCustomers.value.map((item: any) => item.id).join(',');
    await moveToLossPool({
      ids,
      type: '2',
      wxId,
      message: transferToLossForm.message
    });

    ElMessage.success('移交成功');
    transferToLossDialogVisible.value = false;
    selectedCustomers.value = [];
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移交失败');
    }
  } finally {
    transferToLossLoading.value = false;
  }
};

// 预设消息相关方法
const openPresetDialog = () => {
  showPresetDialog.value = true;
  // 打开对话框时自动加载预设消息
  fetchPresetMessages();
};

// 单条添加好友的预设消息对话框
const openSinglePresetDialog = () => {
  showPresetDialog.value = true;
  // 打开对话框时自动加载预设消息
  fetchPresetMessages();
};

const fetchPresetMessages = async () => {
  loadingPresetMessages.value = true;
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const params: any = {
      account: userInfo.username || '',
      current: presetPage.current,
      size: presetPage.size
    };

    // 如果有筛选条件，添加到参数中
    if (presetFilter.value) {
      params.message = presetFilter.value;
    }

    console.log('获取预设消息参数:', params);
    const res = await getAuthenticationList(params);
    console.log('预设消息响应:', res);

    presetMessages.value = res.data?.records || [];
    presetPage.total = res.data?.total || 0;

    console.log('预设消息列表:', presetMessages.value);
  } catch (error) {
    console.error('获取预设消息失败:', error);
    presetMessages.value = [];
  } finally {
    loadingPresetMessages.value = false;
  }
};

const selectPresetRow = (row: any) => {
  selectedPresetMsg.value = row;
};

const handlePresetPageChange = (page: number) => {
  presetPage.current = page;
  fetchPresetMessages();
};

const closePresetDialog = () => {
  selectedPresetMsg.value = null;
  presetFilter.value = '';
  presetPage.current = 1;
};

const confirmPresetMsg = () => {
  if (selectedPresetMsg.value) {
    // 根据当前打开的对话框设置不同的表单
    if (singleAddFriendDialogVisible.value) {
      singleAddFriendForm.message = selectedPresetMsg.value.message;
    } else if (addFriendDialogVisible.value) {
      addFriendForm.message = selectedPresetMsg.value.message;
    }
    showPresetDialog.value = false;
    closePresetDialog();
  }
};

// 显示添加日志对话框
const showAddLogDialog = () => {
  if (!form.id) {
    ElMessage.warning('请先选择一个客户');
    return;
  }

  // 重置表单
  addLogForm.remark = '';
  addLogDialogVisible.value = true;
};

// 提交添加日志
const submitAddLog = async () => {
  try {
    // 验证表单
    await addLogFormRef.value?.validate();

    addLogLoading.value = true;

    // 调用添加日志接口
    const params: AddCustomerPoolLogParams = {
      poolId: form.id!,
      type: 4,
      wxId: getCurrentWxId(),
      remark: addLogForm.remark
    };

    const response = await addCustomerPoolLog(params);

    if (response.code === 200) {
      ElMessage.success('日志添加成功');
      addLogDialogVisible.value = false;

      // 刷新日志列表
      await loadCustomerLogs(form.id!);
    } else {
      ElMessage.error(response.msg || '日志添加失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('添加日志失败:', error);
      ElMessage.error('日志添加失败');
    }
  } finally {
    addLogLoading.value = false;
  }
};

// 批量移交到客户池
const handleBatchMoveToCustomer = async () => {
  if (!selectedLossCustomers.value.length) {
    ElMessage.warning('请选择要移交的客户');
    return;
  }

  try {
    await ElMessageBox.confirm('确定要将选中的客户移交到客户池吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 获取当前操作人的微信ID
    const wxId = getCurrentWxId();
    if (!wxId) {
      ElMessage.error('未找到微信账号信息，请重新登录');
      return;
    }

    const ids = selectedLossCustomers.value.map((item: any) => item.id).join(',');
    await moveToCustomerPool({ ids, type: '1', wxId });
    ElMessage.success('移交成功');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移交失败');
    }
  }
};

// 状态文字映射
const getStatusText = (status: string | number) => {
  const statusMap: Record<string, string> = {
    '1': '待添加',
    '2': '添加中',
    '3': '添加成功',
    '4': '添加失败',
    '5': '手机号异常'
  };
  return statusMap[String(status)] || '未知状态';
};

// 状态样式映射
const getStatusType = (status: string | number) => {
  const typeMap: Record<string, string> = {
    '1': 'info', // 待添加 - 灰色
    '2': 'warning', // 添加中 - 橙色
    '3': 'success', // 添加成功 - 绿色
    '4': 'danger', // 添加失败 - 红色
    '5': 'danger' // 手机号异常 - 红色
  };
  return typeMap[String(status)] || 'info';
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.customer-pool-container {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .operation-section {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
    }

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .notice-tabs {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0;
    }

    :deep(.el-tabs__content) {
      padding: 0;
      margin-top: 15px;
    }
  }

  /* 表单分组样式 */
  .customer-form {
    .form-section {
      margin-bottom: 10px;
      padding: 20px;
      background-color: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .section-title {
        margin: 0 0 20px 0;
        padding: 0 0 10px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        border-bottom: 2px solid #409eff;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 30px;
          height: 2px;
          background-color: #409eff;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }

    :deep(.el-input__wrapper) {
      border-radius: 6px;
    }

    :deep(.el-select) {
      width: 100%;
    }
  }

  /* 导入对话框样式 */
  .import-dialog {
    :deep(.el-dialog__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px 8px 0 0;
      padding: 16px 20px;

      .el-dialog__title {
        font-size: 17px;
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        .el-dialog__close {
          color: white;
          font-size: 16px;

          &:hover {
            color: #f0f0f0;
          }
        }
      }
    }

    :deep(.el-dialog__body) {
      padding: 0;
    }

    :deep(.el-dialog__footer) {
      background: #f8f9fa;
      border-radius: 0 0 8px 8px;
      padding: 16px 20px;
      border-top: 1px solid #e9ecef;
    }
  }

  .import-container {
    padding: 16px;

    .import-steps {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 8px;

      .step-item {
        display: flex;
        align-items: center;
        flex-direction: column;
        text-align: center;
        min-width: 100px;

        .step-number {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          font-size: 14px;
          margin-bottom: 6px;
          box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .step-content {
          h4 {
            margin: 0 0 2px 0;
            font-size: 13px;
            font-weight: 600;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 11px;
            color: #909399;
          }
        }
      }

      .step-arrow {
        font-size: 16px;
        color: #667eea;
        margin: 0 12px;
        font-weight: bold;
      }
    }

    .template-section,
    .upload-section {
      margin-bottom: 16px;

      .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        font-size: 15px;
        font-weight: 600;
        color: #303133;

        .header-icon {
          margin-right: 6px;
          font-size: 16px;
          color: #667eea;
        }
      }
    }

    .template-card {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px;
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        border-color: #667eea;
        box-shadow: 0 2px 12px rgba(102, 126, 234, 0.1);
      }

      .template-info {
        display: flex;
        align-items: center;

        .file-icon {
          font-size: 28px;
          color: #67c23a;
          margin-right: 12px;
        }

        .file-details {
          h5 {
            margin: 0 0 2px 0;
            font-size: 15px;
            font-weight: 600;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 13px;
            color: #909399;
          }
        }
      }

      .download-btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 500;
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 3px 12px rgba(64, 158, 255, 0.4);
        }
      }
    }

    .upload-area {
      :deep(.el-upload-dragger) {
        border: 2px dashed #d9d9d9;
        border-radius: 12px;
        background: #fafbfc;
        transition: all 0.3s ease;
        padding: 40px 20px;

        &:hover {
          border-color: #667eea;
          background: #f0f2ff;
        }

        .upload-content {
          display: flex;
          flex-direction: column;
          align-items: center;

          .upload-icon {
            font-size: 48px;
            color: #c0c4cc;
            margin-bottom: 16px;
          }

          .upload-text {
            .main-text {
              margin: 0 0 8px 0;
              font-size: 16px;
              color: #606266;
              font-weight: 500;
            }

            .sub-text {
              margin: 0;
              font-size: 14px;
              color: #909399;
            }
          }
        }
      }
    }
  }
}

/* 新增客户选项卡样式 */
.add-customer-tabs {
  .el-tabs__header {
    margin-bottom: 20px;
  }

  .el-tabs__content {
    padding: 0;
  }
}

/* 导入容器样式 */
.import-container {
  .import-steps {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;

    .step-item {
      display: flex;
      align-items: center;

      .step-number {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: #409eff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }

      .step-content {
        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          color: #303133;
        }

        p {
          margin: 0;
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .step-arrow {
      margin: 0 20px;
      color: #409eff;
      font-size: 18px;
      font-weight: bold;
    }
  }

  .template-download {
    text-align: center;
    margin-bottom: 30px;

    .download-tip {
      margin-top: 10px;
      color: #909399;
      font-size: 13px;
    }
  }

  .file-upload {
    margin-bottom: 20px;

    .upload-demo {
      .el-upload-dragger {
        border: 2px dashed #d9d9d9;
        border-radius: 6px;
        width: 100%;
        height: 180px;
        text-align: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        &:hover {
          border-color: #409eff;
        }
      }
    }
  }

  .upload-actions {
    text-align: center;

    .el-button {
      margin: 0 10px;
    }
  }

  /* 详情选项卡样式 */
  .detail-tabs {
    .el-tabs__header {
      margin-bottom: 20px;
    }

    .el-tabs__content {
      padding: 0;
      background: #f5f7fa;
      min-height: 400px;
    }
  }

  /* 更多操作菜单样式 */
  .more-actions {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 8px 0;

    .more-action-btn {
      justify-content: flex-start;
      padding: 8px 12px;
      border-radius: 6px;
      transition: all 0.2s ease;
      width: 100%;

      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 新增日志按钮样式
.add-log-section {
  margin: 16px 0;
  text-align: center;
  padding: 12px;
  background-color: #fafbfc;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;

  .el-button {
    border-radius: 16px;
    padding: 8px 16px;
    font-size: 13px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    }
  }
}

// 内联日志样式
.log-item-inline {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f8f9fa;
    border-color: #c0c4cc;
    transform: translateX(2px);
  }

  &:last-child {
    margin-bottom: 0;
  }

  // 不同类型的日志样式
  &.log-add {
    border-left: 4px solid #67c23a;
  }

  &.log-failed {
    border-left: 4px solid #f56c6c;
  }

  &.log-transfer {
    border-left: 4px solid #e6a23c;
  }

  &.log-follow {
    border-left: 4px solid #409eff;
  }
}

.log-icon-inline {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f0f2f5;
  margin-right: 12px;
  flex-shrink: 0;

  .el-icon {
    font-size: 16px;
    color: #606266;
  }
}

// 不同类型的图标颜色
.log-add .log-icon-inline {
  background-color: #f0f9ff;

  .el-icon {
    color: #67c23a;
  }
}

.log-failed .log-icon-inline {
  background-color: #fef0f0;

  .el-icon {
    color: #f56c6c;
  }
}

.log-transfer .log-icon-inline {
  background-color: #fdf6ec;

  .el-icon {
    color: #e6a23c;
  }
}

.log-follow .log-icon-inline {
  background-color: #ecf5ff;

  .el-icon {
    color: #409eff;
  }
}

// 统一的用户标签颜色
.operation-user {
  background-color: #409eff !important;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2) !important;
}

.log-content-inline {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex: 1;
  min-width: 0;
}

.log-main-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;

  .operation-type {
    font-weight: 600;
    color: #303133;
    margin-right: 6px;
    flex-shrink: 0;
    font-size: 14px;
  }

  .operation-user {
    background-color: #409eff;
    color: #fff;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    margin-right: 8px;
    flex-shrink: 0;
  }

  .log-separator {
    color: #c0c4cc;
    margin: 0 6px;
    flex-shrink: 0;
    font-size: 12px;
    font-style: italic;
  }

  .wxt-name-label {
    color: #606266;
    font-size: 12px;
    font-weight: 700;
    margin-right: 4px;
    flex-shrink: 0;
  }

  .wxt-name-content {
    background-color: #f5f7fa;
    color: #303133;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    margin-right: 8px;
    flex-shrink: 0;
    border: 1px solid #e4e7ed;
  }

  .log-remark-label {
    color: #606266;
    font-size: 12px;
    font-weight: 700;
    margin-right: 4px;
    flex-shrink: 0;
  }

  .log-remark-content {
    background-color: #f5f7fa;
    color: #303133;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border: 1px solid #e4e7ed;
    font-style: italic;
  }
}

.log-time-inline {
  color: #909399;
  font-size: 12px;
  margin-left: 12px;
  flex-shrink: 0;
}
</style>

<!-- 全局样式，确保对话框样式生效 -->
<style lang="scss">
.editDialog.el-dialog {
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
}

.el-overlay .editDialog {
  margin-top: 5vh !important;
}

.el-dialog__wrapper .editDialog {
  margin-top: 5vh !important;
}

/* 日志相关全局样式 */
.logs-section {
  padding: 0;

  /* 统计概览样式 */
  .stats-overview {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;

    .stats-item {
      flex: 1;
      display: flex;
      align-items: center;
      padding: 16px;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      transition: all 0.3s ease;

      .stats-icon {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 16px;

        &.add-icon {
          background: linear-gradient(135deg, #67c23a, #85ce61);
          color: white;
        }

        &.failed-icon {
          background: linear-gradient(135deg, #f56c6c, #f78989);
          color: white;
        }

        &.transfer-icon {
          background: linear-gradient(135deg, #409eff, #66b1ff);
          color: white;
        }
      }

      .stats-content {
        .stats-number {
          font-size: 20px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
          margin-bottom: 2px;
        }

        .stats-label {
          font-size: 13px;
          color: #909399;
          font-weight: 500;
        }
      }
    }
  }

  /* 日志容器 */
  .logs-container {
    border-radius: 12px;
    padding: 16px;
    height: 550px;
    overflow-y: auto;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;

      &:hover {
        background: #a8a8a8;
      }
    }

    .logs-list {
      .log-item {
        display: flex;
        margin-bottom: 16px;
        background: #fff;
        border-radius: 12px;
        padding: 16px;
        border-left: 4px solid #e4e7ed;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;

        &:hover {
          transform: translateX(4px);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        }

        &:last-child {
          margin-bottom: 0;
        }

        &.log-item-success {
          border-left-color: #67c23a;

          .log-icon {
            background: linear-gradient(135deg, #67c23a, #85ce61);
          }
        }

        &.log-item-warning {
          border-left-color: #e6a23c;

          .log-icon {
            background: linear-gradient(135deg, #e6a23c, #ebb563);
          }
        }

        &.log-item-default {
          border-left-color: #909399;

          .log-icon {
            background: linear-gradient(135deg, #909399, #a6a9ad);
          }
        }

        .log-icon {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 16px;
          margin-right: 16px;
          flex-shrink: 0;
        }

        .log-content {
          flex: 1;

          .log-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;

            .log-title {
              display: flex;
              align-items: center;
              gap: 12px;

              .operation-type {
                font-size: 16px;
                font-weight: 600;
                color: #303133;
              }

              .operation-tag {
                font-size: 12px;
              }
            }

            .log-time {
              font-size: 12px;
              color: #909399;
              white-space: nowrap;
            }
          }

          .log-body {
            .log-description {
              color: #606266;
              line-height: 1.6;
              font-size: 14px;
            }

            .log-meta {
              display: flex;
              align-items: center;
              gap: 16px;
              font-size: 13px;

              .operator,
              .wx-info {
                display: flex;
                align-items: center;
                gap: 4px;
                color: #909399;

                .el-icon {
                  font-size: 14px;
                }
              }

              .wx-info {
                color: #409eff;
              }
            }
          }
        }
      }
    }

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
  }
}
/* 详情页面样式 */
.detail-tabs .detail-section {
  margin-bottom: 10px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 20px;

  .section-title {
    margin: 0 0 20px 0;
    padding: 0 0 10px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #409eff;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      bottom: -2px;
      width: 30px;
      height: 2px;
      background-color: #409eff;
    }
  }

  .detail-grid {
    padding: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0;

    .detail-item {
      display: flex;
      align-items: flex-start;
      padding: 10px 16px;
      border-bottom: 1px solid #f0f2f5;
      transition: background-color 0.2s;

      &:hover {
        background-color: #fafbfc;
      }

      &:last-child {
        // border-bottom: none;
      }

      &.detail-item-full {
        grid-column: 1 / -1;

        .detail-label {
          width: 130px;
        }

        .detail-value {
          margin-left: 12px;
        }
      }

      .detail-label {
        flex-shrink: 0;
        width: 130px;
        color: #606266;
        font-weight: 600;
        font-size: 13px;
        line-height: 1.4;
        background: #f5f7fa;
        padding: 4px 8px;
        border-radius: 3px;
        margin-right: 12px;
        text-align: center;
        border: 1px solid #e4e7ed;
      }

      .detail-value {
        flex: 1;
        color: #303133;
        font-size: 14px;
        line-height: 1.4;
        word-break: break-all;
        padding: 4px 0;
        font-weight: 500;

        &:empty::before {
          content: '-';
          color: #c0c4cc;
          font-style: italic;
        }
      }
    }
  }
}

/* 预设消息弹窗样式 */
.preset-dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.preset-card-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.preset-card-item {
  position: relative;
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fff;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }

  &.is-selected {
    border-color: #409eff;
    background-color: #f0f9ff;
  }

  .msg-content {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
    max-height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

    &.expanded {
      max-height: none;
      -webkit-line-clamp: unset;
    }
  }

  .selected-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    color: #409eff;
    font-weight: bold;
    font-size: 16px;
  }
}

.no-preset-messages-card {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  font-size: 14px;
}

.preset-dialog-footer {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

/* 换行符处理样式 */
.message-content {
  // max-height: 60px;
  // overflow: hidden;
  // line-height: 1.4;
}

.message-line {
  margin-bottom: 2px;

  &:last-child {
    margin-bottom: 0;
  }
}

.remark-content {
  line-height: 1.5;
}

.remark-line {
  margin-bottom: 4px;

  &:last-child {
    margin-bottom: 0;
  }

  &:empty {
    display: none;
  }
}

// /* 表格中的消息内容悬停展开 */
// .message-content:hover {
//   max-height: none;
//   overflow: visible;
//   background-color: #f5f7fa;
//   padding: 4px;
//   border-radius: 4px;
//   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
//   z-index: 10;
//   position: relative;
// }
</style>
